var wxTimer = function (initObj) {
    initObj = initObj || {};
    this.complete = initObj.complete;					//结束任务（方法）
    this.expired = initObj.expired;					    //过期执行（方法）

    this.intervarID;									//计时ID
    this.expired_at = initObj.expired_at || "00:00:00";	//过期时间
}

wxTimer.prototype = {
    //开始
    start: function (self) {
        let that = this;
        let expired_at = that.expired_at; // 过滤时间的小数点
        expired_at = expired_at.substring(0, expired_at.indexOf('.'));   
        expired_at = new Date(expired_at.replace(/-/g, "/")).getTime();
        // expired_at = new Date(expired_at).getTime(); // ios下不执行,返回为null
        let nowTime = new Date().getTime();
        let remaining = (expired_at - nowTime); //计算剩余的毫秒数
        // 过期
        if (remaining < 0) {
            if (that.expired) {
                that.expired();
            }
            return
        }
        function begin() {
            // 过期
            // if (remaining < 0) {
            //     if (that.expired) {
            //         that.expired();
            //     }
            //     that.stop();
            // }else{

                let hours = parseInt(remaining / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
                let minutes = parseInt(remaining / 1000 / 60 % 60, 10);//计算剩余的分钟
                let seconds = parseInt(remaining / 1000 % 60, 10);//计算剩余的秒数
                hours = checkTime(hours);
                minutes = checkTime(minutes);
                seconds = checkTime(seconds);
                // 结束任务
                if (hours <= 0 && minutes <= 0 && seconds <= 0) {
                    if (that.complete) {
                        that.complete();
                    }
                    that.stop();
                }
                if (hours >= 0 || minutes >= 0 || seconds >= 0) {
                    self.setData({
                        ['timer.remaining']: hours + ":" + minutes + ":" + seconds
                    });
                }
                remaining = remaining - 1000;            
            // }
        }
        function checkTime(timer){
            if (timer < 10){
                timer = "0" + timer;
            }
            return timer;
        }
        // begin();
        this.intervarID = setInterval(begin, 1000);
    },
    //结束
    stop: function () {
        clearInterval(this.intervarID);
    }
}

module.exports = wxTimer;